package com.zut.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zut.eduservice.entity.Usertable;
import com.zut.eduservice.entity.excel.UserData;
import com.zut.eduservice.entity.vo.ClassInfo;
import com.zut.eduservice.service.UsertableService;
import com.zut.servicebase.exceptionhandler.GuliException;

public class UserExcelListener extends AnalysisEventListener<UserData> {
    //因为ExcelListener不能交给spring进行管理，需要自己new，不能注入其他对象
    //不能实现数据库操作
    String  oneclassId=null;
    String twoclassNmae=null;
    public UsertableService usertableService;
    public UserExcelListener() {}
    public UserExcelListener(UsertableService usertableService, String classId, String classNmae) {
        this.usertableService = usertableService;

       oneclassId=classId;
       twoclassNmae=classNmae;
    }




    @Override
    public void invoke(UserData userData, AnalysisContext analysisContext) {
        //不判定重复插入数据
       /* System.out.println(userData);
        if(userData == null) {
            throw new GuliException(20001,"文件数据为空");
        }
        Usertable usertable = new Usertable();
       if(usertable.getStudentId()!=userData.getStudentId()) {
           usertable.setStudentId(userData.getStudentId());
           usertable.setGrade(userData.getGrade());
           usertable.setStudentName(userData.getName());
           usertable.setSex(userData.getSex());
           usertableService.save(usertable);
       }*/
        //判定重复插入数据

        System.out.println(oneclassId);
        if(userData == null) {
            throw new GuliException(20001,"文件数据为空");
        }
       Usertable existOne = this.existOne(usertableService, userData.getStudentId());
        if(existOne == null) { //没有相同学生id，进行添加
            existOne = new Usertable();
            existOne.setStudentId(userData.getStudentId());
            existOne.setSex(userData.getSex());
            existOne.setStudentName(userData.getName());
            existOne.setGrade(userData.getGrade());
            existOne.setSign(0);
            existOne.setClassId(oneclassId);
            existOne.setClassName(twoclassNmae);
            usertableService.save(existOne);
        }

    }

        private Usertable existOne(UsertableService usertableService,String studentId) {
            QueryWrapper<Usertable> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id",studentId);
            wrapper.eq("class_id",oneclassId);
            Usertable oneTable = usertableService.getOne(wrapper);
            return oneTable;
        }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
